package com.marcowu.study.spb.tracing.zipkin;

import brave.Tracing;
import brave.opentracing.BraveTracer;
import brave.propagation.B3Propagation;
import brave.propagation.ExtraFieldPropagation;
import brave.propagation.Propagation;
import io.opentracing.noop.NoopTracerFactory;
import io.opentracing.Tracer;
import zipkin2.Span;
import zipkin2.reporter.AsyncReporter;
import zipkin2.reporter.okhttp3.OkHttpSender;

import java.util.Arrays;

public class TracerBuiler {

  public static Tracer getZipkinTracer(String serviceName) {
    try {
      // Configure a reporter, which controls how often spans are sent
      //   (the dependency is io.zipkin.reporter2:zipkin-sender-okhttp3)
      final OkHttpSender sender = OkHttpSender.create("http://localhost:9411/api/v2/spans");
      final AsyncReporter<Span> spanReporter = AsyncReporter.create(sender);

      // If you want to support baggage, indicate the fields you'd like to
      // whitelist, in this case "country-code" and "user-id". On the wire,
      // they will be prefixed like "baggage-country-code"
      final ExtraFieldPropagation.Factory propagationFactory = ExtraFieldPropagation.newFactoryBuilder(B3Propagation.FACTORY)
                    .addPrefixedFields("baggage-", Arrays.asList("country-code", "user-id"))
                    .build();

      // Now, create a Brave tracing component with the service name you want to see in Zipkin.
      //   (the dependency is io.zipkin.brave:brave)
      final Tracing braveTracing = Tracing.newBuilder()
                    .localServiceName(serviceName)
                    .propagationFactory(propagationFactory)
                    .spanReporter(spanReporter)
                    .build();

      // use this to create an OpenTracing Tracer
      final Tracer tracer = BraveTracer.create(braveTracing);

       return tracer;
    } catch (Exception e) {
      e.printStackTrace();
      return NoopTracerFactory.create();
    }
  }
}
